<template>
  <div>

    <div style="display: flex; justify-content: center;">
      <el-row type="flex" style="width: 60%;">
        <el-button icon="el-icon-back" @click="$router.push('/worker/plaza/recommended')" plain>返回列表</el-button>
      </el-row>
    </div>

    <el-main
        class="detail-box"
        v-loading="loading"
        element-loading-text="正在加载"
        element-loading-spinner="el-icon-loading">
      <div class="container-title">
        <img src="../../../assets/image/task-details.png" alt="" style="width: 150px">
      </div>
      <el-descriptions
          class="margin-top"
          :column="1"
          border>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-edit"></i>
            测试名称
          </template>
          {{ form.taskname }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            发包方
          </template>
          {{ form.username }}
        </el-descriptions-item>
<!--        <el-descriptions-item>-->
<!--          <template slot="label">-->
<!--            <i class="el-icon-setting"></i>-->
<!--            测试类型-->
<!--          </template>-->
<!--          {{ form.type }}-->
<!--        </el-descriptions-item>-->
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-time"></i>
            截止日期
          </template>
          {{ form.deadline }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user-solid"></i>
            需求人数
          </template>
          {{ form.need_num }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
            任务描述
          </template>
          {{ form.description }}
        </el-descriptions-item>

      </el-descriptions>
      <device-requirements-view :value="form.deviceRequirement"></device-requirements-view>
      <el-row type="flex" justify="center">
        <el-col :span="8">
          <el-button type="warning" @click="handleGetApp()">
            下载待测应用
          </el-button>
        </el-col>
        <el-col :span="8">
          <el-button type="success" @click="handleGetDoc()">
            下载测试文档
          </el-button>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center" style="margin: 30px">
        <el-button id="get-task-btn" type="danger" v-if="!got" disabled>
          请点击一个节点任务查看详细并领取
        </el-button>
        <el-button type="danger" v-else-if="got" disabled>
          已领取
        </el-button>
      </el-row>

      <el-card style="margin: 30px">
        <task-map
            v-model="nodes"
            mode="display"
            @click-node="handleClickNode"
            :click-menu-config="clickMenuConfig"
            :tooltip-config="tooltipConfig"
            :node-state-styles="stateStyles"
            :node-states="nodeStates"
        >

        </task-map>
      </el-card>
      <el-dialog
          :visible.sync="subTaskDialogVisible"
          width="800px"
          :destroy-on-close="true"
      >
      <span>
        <subTaskInfo :id="pointId" @acceptTask="handleAcceptsubTask"></subTaskInfo>
      </span>
        <span slot="footer" class="dialog-footer">
      </span>
      </el-dialog>
    </el-main>
  </div>
</template>

<script>
import {Debounce} from "@/utils/Debounce.js";
import {getCollaborationTaskDetail, getCollaborationTaskGroups, getTaskDetailsByTaskID, getTaskFile} from "@/api/task";
import {downloadFile} from "@/api/file";
import {whetherClaimedCertainTask} from "@/api/worker";
import ClaimTask from "@/views/new/worker/claim-task/ClaimTask";
import DeviceRequirementsView from "@/components/new/device-requirements-card/DeviceRequirementsView";
import IconFont from "@/components/new/iconfont/IconFont";
import TaskMap from "@/components/new/task-map/TaskMap";
import subTaskInfo from "@/components/worker/new/subTaskInfo";
export default {
  name: "multiUserTaskDetail",
  components: {IconFont, DeviceRequirementsView, ClaimTask, TaskMap,subTaskInfo},
  data() {
    return {
      form: {
        taskname: '',
        environment: '',
        deadline: '',
        username: '',
        need_num: '',
        description: '',
      },
      pointId:888,
      nodes: [],
      clickNodeEvents: [],
      subTaskDialogVisible: false,

      stateStyles: {
        disabled: {
          stroke: '#6c6c6c',
          fill: '#dbdbdb'
        }
      },
      nodeStates: {
        disabled: new Set([1, 2])
      }

      // ljzc's
      // got: false,
      // taskId: -1,
      //
      // taskGroups: [],
      // collaborationTask: {
      //   subTasks: []
      // },
      // loadingTask: false,
      // currentGroupIdx: '',
      // stateStyles: {
      //   disabled: {
      //     stroke: '#6c6c6c',
      //     fill: '#dbdbdb'
      //   }
      // },
      // unfinishedTasks: {
      //   disabled: new Set(),
      //   selected: new Set()
      // },
      // currentReportId: undefined

    };
  },

  computed: {
    loading() {
      return this.form['taskname'] === '';
    },
    taskId() {
      return this.$route.params.taskid;
    },


    // ljzc's
    // subTasks(){
    //   if(this.collaborationTask){
    //     return this.collaborationTask.subTasks;
    //   }else{
    //     return []
    //   }
    // },
    // tooltipConfig(){
    //   return {
    //     getContent: (task) => {
    //       if(this.taskGroups.length !== 0){
    //         const reportViewResult = this.taskGroups[this.currentGroupIdx].filter(report => {
    //           return report.taskId === task.id;
    //         });
    //
    //         if(reportViewResult.length !== 0){
    //           const result = reportViewResult[0]
    //           return `<div>${result.workerName}</div>`
    //         }
    //       }
    //       return '...';
    //
    //     }
    //   }
    // }

    clickMenuConfig(){
      return {
        getContent: (task) => {
          return `
          <div>
            <div>${JSON.stringify(task)}</div>
            <button class="click-menu-button">按钮</button>
          </div>
          `
        },
        handleMenuClick: (target, task) => {
          if(target.classList.contains('click-menu-button')){
            this.$message.info(JSON.stringify(task));
          }
        }
      }
    },
    tooltipConfig(){
      return {
        getContent: (task) => {
          return `
          <div>
            ${JSON.stringify(task)}
          </div>
          `;

        }
      }
    }




  },
  mounted() {
    new Promise(resolve => {
      setTimeout(() => {
        this.nodes = [{
          id: 1,
          dependencies: [2, 3]
        },
          {
            id: 2,
            dependencies: []
          },
          {
            id: 3,
            dependencies: [4]
          },{
            id: 4,
            dependencies: []
          }]
      }, 1000)
    })
    // ljzc's
    // this.loadCollaborationTask().then(() => {
    //   return this.loadTaskGroups();
    // })
    //     .then(() => {
    //       this.refreshGroup(0)
    //     })
    //     .catch(e => {
    //       this.$message.error(e.message);
    //     }).finally(() => {
    //   this.loadingTask = false;
    // });
  },

  created() {
    this.getDetailObj();
    this.getTaskStatus();
    this.taskId = this.$route.params.taskid;
  },

  methods: {

    // 组件挂载后，用于加载任务信息表格
    async getDetailObj() {
      const res = await getTaskDetailsByTaskID(this.$route.params.taskid);
      if (res.code !== 200) {
        return this.$message.error(res.msg);
      }

      for (let key of Object.keys(res.data)) {
        if (key !== 'type') {
          this.form[key] = res.data[key];
        } else {
          if (res.data['type'] === 'function_test') this.form['type'] = '功能测试';
          else if (res.data['type'] === 'performance_test') this.form['type'] = '性能测试';
          else if (res.data['type'] === 'bug_explore') this.form['type'] = 'Bug探索';
        }
      }
    },


    async getTaskStatus() {
      const workerid = sessionStorage.getItem('userid');
      const taskid = this.$route.params.taskid;
      const res = await whetherClaimedCertainTask(taskid, workerid);
      if (res.code === 200) {
        this.got = true;
      }
    },


    handleGetApp: Debounce(function () {
      this.$message('正在下载待测应用……');
      const taskId = this.$route.params.taskid
      let url = null
      const data = {
        taskId: taskId,
        kind: "2"
      }
      getTaskFile(data).then(res => {
        url = res.name
        downloadFile(url).then(res => {
        })
      });
    }, 1000),


    handleGetDoc: Debounce(function () {
      this.$message('正在下载测试文档……');
      const taskId = this.$route.params.taskid
      let url = null
      const data = {
        taskId: taskId,
        kind: "3"
      }
      getTaskFile(data).then(res => {
        url = res.name
        downloadFile(url).then(res => {
          console.log(res);
        })
      });
    }, 1000),

    handleClickNode(nodeId){
      this.clickNodeEvents.push(nodeId);
      this.pointId=nodeId;
      this.subTaskDialogVisible=true;
    },
    handleAcceptsubTask(pointId){
      this.$message.success('Accept task, pointId = '+pointId);
      this.subTaskDialogVisible=false;
    }

    // ljzc's
    // loadTaskGroups(){
    //   this.loadingTask = true;
    //   return getCollaborationTaskGroups(this.$route.params.taskId)
    //       .then(res => {
    //         if(res.code === 200){
    //           this.taskGroups = res.data;
    //         }else{
    //           throw new Error(res.msg);
    //         }
    //       })
    // },
    // loadCollaborationTask(){
    //   this.loadingTask = true;
    //   return getCollaborationTaskDetail(this.$route.params.taskId)
    //       .then(res => {
    //         if(res.code === 200){
    //           this.collaborationTask = res.data;
    //         }else{
    //           throw new Error(res.msg);
    //         }
    //       })
    // },
    // refreshGroup(idx){
    //   this.currentReportId = undefined;
    //   if(this.taskGroups.length !== 0 && this.subTasks.length !== 0){
    //     const exist = new Set(this.taskGroups[idx].map(item => item.taskId));
    //     this.unfinishedTasks = {selected: new Set(), disabled: new Set(this.subTasks.map(task => task.id).filter(id => !exist.has(id)))};
    //   }
    // },
    // handleClickNode(taskId){
    //   if(this.taskGroups.length !== 0){
    //
    //     const target = this.taskGroups[this.currentGroupIdx].filter(reportView => {
    //       return reportView.taskId === taskId;
    //     });
    //     if(target.length !== 0){
    //       this.currentReportId = target[0].reportId;
    //       this.unfinishedTasks = {...this.unfinishedTasks, selected: new Set([target[0].taskId])}
    //     }
    //   }
    // }
  },


  watch: {
    // ljzc's
    // currentGroupIdx(idx){
    //   this.refreshGroup(idx);
    // },

  },
}
</script>

<style scoped>
.detail-box {
  margin: 10px auto;
  width: 60%;

  border: 1px solid #DCDFE6;
  box-shadow: 0 0 8px #909399;

  padding: 3% 3%;

  background-color: #ffffff;
}

.click-menu-button{
  border-style: none;
  padding: 2px 5px;
  background-color: dodgerblue;
  color: white;
  border-radius: 5px;
}
</style>
